<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationStyle: 'default',
    navigationBarTitleText: '首页',
  },
}
</route>
<template>
  <div class="container">
    <div class="top p-xy bg-[#49b65f] box-border text-white">
      <div class="flex items-center justify-between">
        <div class="flex items-center">
          <image src="@/static/images/weather.png" mode="widthFix" class="w-[40px]"></image>
          <div class="ml-2 text-lg text-[20px] font-bold">{{ weatherInfo.temperature }}℃</div>
          <div class="ml-4 font-thin">{{ weatherInfo.city }}</div>
        </div>
        <div class="font-thin">{{ today()?.dateStr }} {{ today()?.weekDay }}</div>
      </div>
      <div class="flex items-center justify-between mt-4">
        <div
          class="text-[#49b65f] px-4 py-1 flex items-center justify-center rounded-2 min-h-[44px] bg-white gap-3 cursor-pointer font-bold w-[48%] box-border"
          @click="toRecord"
        >
          <image src="@/static/images/ffr.png" mode="widthFix" class="w-[20px]"></image>
          <span>农事财务记录</span>
        </div>
        <div
          class="text-[#49b65f] px-4 py-1 flex items-center justify-center rounded-2 min-h-[44px] bg-white gap-3 cursor-pointer font-bold w-[48%] box-border"
          @click="jumpPage('/pages/user/feedback/index')"
        >
          <image src="@/static/images/opinion1.png" mode="widthFix" class="w-[20px]"></image>
          <span>意见反馈</span>
        </div>
      </div>
    </div>
    <div class="bg-[#f7f7f7] box-border py-6 px-4 min-h-[80vh]">
      <div class="text-[16px] font-bold">需求报送</div>
      <div class="rounded-2 bg-white mt-2">
        <div class="w-full h-[110px] flex" style="border-bottom: 1px solid #e6f4e6">
          <template v-for="(item, index) in list" :key="index">
            <div
              :style="{
                borderRight: index % 2 === 0 ? '1px solid #e6f4e6' : 'none',
              }"
              class="w-1/2 h-[110px] flex flex-col justify-center items-center gap-3 box-border"
              v-if="index < 2"
              @click="handleNeed(item)"
            >
              <image :src="iconMap[item.title]" mode="heightFix" class="h-[30px]"></image>
              <span class="text-[14px] text-gray-500">{{ item.title }}</span>
            </div>
          </template>
          <!--          <div class="w-1/2 h-[110px] flex flex-col justify-center items-center gap-3 box-border">-->
          <!--            <image src="@/static/images/loan.png" mode="heightFix" class="h-[30px]"></image>-->
          <!--            <span class="text-[14px] text-gray-500">农业贷款</span>-->
          <!--          </div>-->
        </div>
        <div class="w-full h-[110px] flex" style="border-bottom: 1px solid #e6f4e6">
          <template v-for="(item, index) in list" :key="index">
            <div
              :style="{
                borderRight: index % 2 === 0 ? '1px solid #e6f4e6' : 'none',
              }"
              class="w-1/2 h-[110px] flex flex-col justify-center items-center gap-3 box-border"
              v-if="index === 2 || index === 3"
              @click="handleNeed(item)"
            >
              <image :src="iconMap[item.title]" mode="heightFix" class="h-[30px]"></image>
              <span class="text-[14px] text-gray-500">{{ item.title }}</span>
            </div>
          </template>
          <!--          <div-->
          <!--            style="border-right: 1px solid #e6f4e6"-->
          <!--            class="w-1/2 h-[110px] flex flex-col justify-center items-center gap-3 box-border"-->
          <!--          >-->
          <!--            <image src="@/static/images/apmaes.png" mode="heightFix" class="h-[30px]"></image>-->
          <!--            <span class="text-[14px] text-gray-500">农业种植机械设备服务</span>-->
          <!--          </div>-->
          <!--          <div class="w-1/2 h-[110px] flex flex-col justify-center items-center gap-3 box-border">-->
          <!--            <image src="@/static/images/ass.png" mode="heightFix" class="h-[30px]"></image>-->
          <!--            <span class="text-[14px] text-gray-500">农资服务(农业种植所需)</span>-->
          <!--          </div>-->
        </div>
        <div class="w-full h-[110px] flex" style="border-bottom: 1px solid #e6f4e6">
          <template v-for="(item, index) in list" :key="index">
            <div
              :style="{
                borderRight: index % 2 === 0 ? '1px solid #e6f4e6' : 'none',
              }"
              class="w-1/2 h-[110px] flex flex-col justify-center items-center gap-3 box-border"
              v-if="index === 4 || index === 5"
              @click="handleNeed(item)"
            >
              <image :src="iconMap[item.title]" mode="heightFix" class="h-[30px]"></image>
              <span class="text-[14px] text-gray-500">{{ item.title }}</span>
            </div>
          </template>
          <!--          <div-->
          <!--            style="border-right: 1px solid #e6f4e6"-->
          <!--            class="w-1/2 h-[110px] flex flex-col justify-center items-center gap-3 box-border"-->
          <!--          >-->
          <!--            <image src="@/static/images/employment.png" mode="heightFix" class="h-[30px]"></image>-->
          <!--            <span class="text-[14px] text-gray-500">劳务雇佣</span>-->
          <!--          </div>-->
          <!--          <div class="w-1/2 h-[110px] flex flex-col justify-center items-center gap-3 box-border">-->
          <!--            <image src="@/static/images/sales.png" mode="heightFix" class="h-[30px]"></image>-->
          <!--            <span class="text-[14px] text-gray-500">农产品出售</span>-->
          <!--          </div>-->
        </div>
        <div class="w-full h-[110px] flex" style="border-bottom: 1px solid #ffffff">
          <template v-for="(item, index) in list" :key="index">
            <div
              :style="{
                borderRight: index % 2 === 0 ? '1px solid #e6f4e6' : 'none',
              }"
              class="w-1/2 h-[110px] flex flex-col justify-center items-center gap-3 box-border"
              v-if="index === 6 || index === 7"
              @click="handleNeed(item)"
            >
              <image :src="iconMap[item.title]" mode="heightFix" class="h-[30px]"></image>
              <span class="text-[14px] text-gray-500">{{ item.title }}</span>
            </div>
          </template>
          <!--          <div-->
          <!--            style="border-right: 1px solid #e6f4e6"-->
          <!--            class="w-1/2 h-[110px] flex flex-col justify-center items-center gap-3 box-border"-->
          <!--          >-->
          <!--            <image src="@/static/images/recycle.png" mode="heightFix" class="h-[30px]"></image>-->
          <!--            <span class="text-[14px] text-gray-500">农业废弃物回收</span>-->
          <!--          </div>-->
          <!--          <div class="w-1/2 h-[110px] flex flex-col justify-center items-center gap-3 box-border">-->
          <!--            <image src="@/static/images/other-need.png" mode="heightFix" class="h-[30px]"></image>-->
          <!--            <span class="text-[14px] text-gray-500">其他需求</span>-->
          <!--          </div>-->
        </div>
      </div>
    </div>
    <!-- 需求报送 -->
    <NsOverlay
      v-model:visible="visible"
      height="630rpx"
      footerTop="86rpx"
      okText="确认报送"
      cancelText="立即取消"
      @ok="handleOk"
    >
      <div class="text-center tip-text" style="padding-top: 154rpx; line-height: 48rpx">
        即将为您报送
        <div>
          <span class="text-[#56b756]">{{ need }}</span>
          需求
        </div>
        请您确认是否需要报送
      </div>
    </NsOverlay>
    <!-- 其他需求报送 -->
    <!-- 需求报送表单 -->
    <wd-action-sheet v-model="show">
      <div class="pt-14.5 pb-16 bg-[#fff]">
        <wd-form ref="form" :model="model">
          <wd-cell-group>
            <div class="form-item pb-15">
              <div
                class="form-label form-label-required text-[#666] text-[16px]"
                style="margin-left: 32rpx"
              >
                需求内容
              </div>
              <div class="form-value">
                <wd-textarea
                  label=""
                  label-width="100px"
                  prop="content"
                  custom-textarea-class="feedback-textarea"
                  :maxlength="200"
                  v-model="model.content"
                  placeholder="请输入您的报送需求"
                  :clearable="false"
                  :rules="[{ required: true, message: '请填写内容' }]"
                />
                <div class="count text-[#666] text-[16px]">
                  {{ model.content ? model.content.length : 0 }}/200
                </div>
                <div class="clear text-[#666] text-[16px]" @click.stop="model.content = ''">
                  清除
                </div>
              </div>
            </div>
          </wd-cell-group>
        </wd-form>
        <div class="confirm" @click="confirmNeed">确认报送</div>
      </div>
    </wd-action-sheet>
    <NsOverlay
      v-model:visible="successVisible"
      height="462rpx"
      footerTop="34rpx"
      okText="确定"
      buttonSize="small"
      :showCancel="false"
    >
      <div class="text-center tip-text" style="padding-top: 68rpx; line-height: 48rpx">
        <image src="@/static/images/check-success.png" mode="widthFix" class="w-[50px]"></image>
        <div class="mt-5 text-[#666]">
          需求已经为您报送
          <br />
          工作人员将与您联系
        </div>
      </div>
    </NsOverlay>
  </div>
</template>

<script lang="ts" setup>
import PLATFORM from '@/utils/platform'

import { useToast } from 'wot-design-uni'
// eslint-disable-next-line import/extensions
import amap from '@/utils/amap-wx.130.js'
import { getNeedFirstPage, needSubmit, weather } from '@/service/need'
import NsOverlay from '@/components/ns-overlay.vue'
import p1 from '@/static/images/land-transfer.png'
import p2 from '@/static/images/loan.png'
import p3 from '@/static/images/apmaes.png'
import p4 from '@/static/images/nz.png'
import p5 from '@/static/images/employment.png'
import p6 from '@/static/images/sales.png'
import p7 from '@/static/images/recycle.png'
import p8 from '@/static/images/other-need.png'

const iconMap = {
  土地流转: p1,
  农业贷款: p2,
  农业种植机械设备服务: p3,
  '农资服务（农业种植所需）': p4,
  劳务雇佣: p5,
  农产品出售: p6,
  农业废弃物回收: p7,
  其他需求: p8,
}
const myAmapFun = ref(null)
const toast = useToast()
defineOptions({
  name: 'Home',
})

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 跳转农事财务记录
function toRecord() {
  uni.switchTab({
    url: '/pages/record/index',
  })
}

// 跳转页面
function jumpPage(url: string) {
  uni.navigateTo({
    url,
  })
}
// 获取位置
function getLocation() {
  // uni.getLocation({
  //   type: 'wgs84',
  //   success: function (res) {
  //     console.log(res, '位置信息')
  //   },
  //   fail(result) {
  //     console.log(result, '位置信息失败')
  //     toast.show('获取位置失败，请检查定位权限')
  //   },
  // })
}
// 获取天气
const today = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  // 补零
  const monthStr = month < 10 ? `0${month}` : month
  const dayStr = day < 10 ? `0${day}` : day
  const weekDay = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][
    date.getDay()
  ]
  return {
    dateStr: `${year}-${monthStr}-${dayStr}`,
    weekDay,
  }
}

const weatherInfo = ref({})
const isLocationAuth = ref(false)
watch(
  () => uni.getAppAuthorizeSetting(),
  (val) => {
    console.log(val, '授权信息')
    if (val.locationAuthorized === 'authorized') {
      isLocationAuth.value = true
      getWeather && getWeather()
    }
  },
  { immediate: true, deep: true },
)
const getWeather = () => {
  myAmapFun.value.getRegeo({
    success: async function (data) {
      // 成功回调
      const city = data[0].regeocodeData.addressComponent.city
      const res: IResData<any> = await weather(city)
      console.log(res, '天气')
      if (res.code === 1) {
        weatherInfo.value = res.data
      }
      // console.log(city, '位置信息')
    },
    fail: function (info) {
      // 失败回调
      console.log(info)
    },
  })
}
// 获取首页需求
const list = ref<INeedData[]>([])
const getNeed = async () => {
  const res: IResData<INeedData[]> = await getNeedFirstPage()
  if (res.code === 1) {
    list.value = res.data
  }
}
const submitParams = reactive<INeedParams>({
  id: 0,
  content: '',
})
const handleNeed = (item: INeedData) => {
  console.log(item, 'item')
  const params: INeedParams = {
    id: item.id,
    content: '',
  }
  submitParams.id = item.id
  if (item.other === 1) {
    // 其他需求
    show.value = true
  } else {
    need.value = item.title
    visible.value = true
  }
}
// 弹窗
const visible = ref<boolean>(false)
const successVisible = ref<boolean>(false)
const need = ref<string>('')
const handleOk = async () => {
  const res: any = await needSubmit(submitParams)
  if (res.code === 1) {
    visible.value = false
    nextTick(() => {
      successVisible.value = true
      need.value = ''
    })
  }
}

const show = ref(false)

const model = reactive<{
  // 内容
  content: string
}>({
  content: '',
})
const confirmNeed = async () => {
  submitParams.content = model.content
  const res: any = await needSubmit(submitParams)
  if (res.code === 1) {
    show.value = false
    nextTick(() => {
      successVisible.value = true
      model.content = ''
    })
  }
}
// 测试 uni API 自动引入
onLoad(async () => {
  myAmapFun.value = new amap.AMapWX({ key: import.meta.env.VITE_GD_KEY }) // 初始化高德地图sdk
  getWeather()
  await getNeed()
  // getLocation()
})
</script>

<style scoped>
.main-title-color {
  color: #d14328;
}

.form-label {
  margin-bottom: 20rpx;
}
.form-label-required {
  position: relative;
  padding-left: 8px;
}

.form-label-required::before {
  content: '*';
  position: absolute;
  bottom: 0;
  left: 0;
  font-size: 12px;
  color: #f61515;
}

.form-value {
  position: relative;
  background-color: #f7f7f7;
}

.count,
.clear {
  position: absolute;
  z-index: 2;
  bottom: 40rpx;
  left: 50rpx;
  background-color: #f7f7f7;
}

.clear {
  left: unset;
  right: 50rpx;
}

:deep(.wd-textarea__value) {
  height: 268rpx !important;
  background-color: #f7f7f7 !important;
}

:deep(.feedback-textarea) {
  padding: 16rpx 20rpx !important;
  height: 268rpx !important;
  background-color: #f7f7f7 !important;
  border-radius: 8px !important;
}

:deep(.wd-textarea__value) {
  border-radius: 16rpx;
}

:deep(.wd-textarea__suffix) {
  display: none;
}

.confirm {
  border-radius: 4px;
  background: #56b756;
  margin: auto;
  width: 690rpx;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}
</style>
